<?php

// TODO: Generalizar esto a un abmcontrller
/*
 * Es un ejemplo del controlador que se ocupa de loguear y desloguear un usuario
 * La idea es heredar esta clase y extenderla a gusto.
 */
/*
 * Esto podria agregarse a Ext_Controller o como un plugin.
 */
class Ext_Controller_RoleController extends Ext_Controller_SecureAction
{
    protected $_roleModel = 'Ext_Model_Role';
    protected $_aclRuleModel = 'Ext_Model_AclRule';
    protected $_resourceModel = 'Ext_Model_Resource';

    static $PERMISSIONS = array( 'allow'=>'allow', 'deny'=>'deny');
    
    public function listAction()
    {
        $roleDb = Ext_Generic_Model::get( $this->_roleModel, $this->_db );
        $paginator = new Ext_Paginator( 
        	new Zend_Paginator_Adapter_Iterator( 
        		$roleDb->fetchAll( null, 'name' ) 
        	)
        );
        $paginator->setCurrentPageNumber( $this->_request->getParam( "page" ) );
        $this->view->paginator = $paginator;
    }

    public function editAction()
    {
        $roleDb = Ext_Generic_Model::get( $this->_roleModel, $this->_db );
        
        $roleId = $this->_request->getParam( 'roleId' );
        if ( empty( $roleId ) ) {
            $this->view->role = $roleDb->createRow();
        } else {
            $this->view->role = $roleDb->find( $roleId )->current();
            if ( empty( $this->view->role ) ) {
                $this->addError( "role not found" );
                $this->_redirect(
                    $this->view->url( 
		        		array(
		        			'controller'=>'role' 
		        			,'action'=>'aclList'
		        		)
		        		, "default"
		        	)
                );
                return;
            }
        }
        
        $form = new Ext_Forms_EditRole( );
        $form->cancel->setLabel( 'Cancelar' )->setAttrib( 'onclick', "document.location='" .
        	$this->view->url( 
		    	array(
		        	'controller'=>'role' 
		        	,'action'=>'aclList'
		        )
		        , "default"
		    )
        	."'" );
        $form->accept->setLabel( 'Aceptar' );
        
        $data = $this->_request->getParams();
        
        if ( $this->_request->isPost() ) {
            
            $isValid = $form->isValid( $data );
            
            // TODO: Make a validator for this
            if ( empty( $this->view->role->name ) ) {
                $role = $roleDb->getRoleId( $data[ 'name' ] );
                if ( ! empty( $role ) ) {
                    $this->addError( "El nombre del role ya existe" );
                    $isValid = false;
                }
            }
            
            if ( $isValid ) {
                $extraData = array( 
					"name" => strtolower( trim( $data[ "name" ] ) )
                );
                $this->view->role->setFromArray( $extraData );
                $this->view->role->save();
                
                $this->_redirect(
                    $this->view->url( 
		        		array(
		        			'controller'=>'role' 
		        			,'action'=>'list'
		        		)
		        		, "default"
		        	)
                );
                return;
            }
        }
        
        // TODO: generalizar esto
        if ( ! isset( $data[ 'name' ] ) ) {
            $data[ 'name' ] = $this->view->role->name;
        }
        $data[ 'name' ] = strtolower( trim($data[ 'name' ] ) );
        $form->setAction( 
            $this->view->url( 
        		array(
        			'controller'=>'role' 
        			,'action'=>'edit'
        			,'roleId' => $this->view->role->role_id
        		)
        		, "default"
        	)        
        );
        $form->populate( $data );
        $this->view->form = $form;
    }

    public function acllistAction()
    {
        $roleId = $this->_request->getParam( 'roleId' );
        if ( empty( $roleId ) ) {
            $this->addError( "roleId not found" );
            $this->_redirect(
	            $this->view->url( 
	        		array(
	        			'controller'=>'role' 
	        			,'action'=>'list'
	        		)
	        		, "default"
	        	)        
            );
            return;
        }

        $roleDb = Ext_Generic_Model::get( $this->_roleModel, $this->_db );
        $this->view->role = $roleDb->find( $roleId )->current();
        if ( empty( $this->view->role ) ) {
            $this->addError( "Role not found" );
            $this->_redirect(
	            $this->view->url( 
	        		array(
	        			'controller'=>'role' 
	        			,'action'=>'list'
	        		)
	        		, "default"
	        	)        
            );
            return;
        }
        $this->view->acls = $this->view->role->findExt_Model_AclRule( $this->view->role->select()->order('resource_id, priority, operation, permission') );
        $paginator = new Ext_Paginator( new Zend_Paginator_Adapter_Iterator( $this->view->acls ) );
        $paginator->setCurrentPageNumber( $this->_request->getParam( "page" ) );
        $this->view->paginator = $paginator;

    }

    public function acleditAction()
    {
        $aclDb = Ext_Generic_Model::get( $this->_aclRuleModel, $this->_db );

        $roleId = $this->_request->getParam( 'roleId' );
        if ( empty( $roleId ) ) {
            $this->addError( "role not found" );
            $this->_redirect(
	            $this->view->url( 
	        		array(
	        			'controller'=>'role' 
	        			,'action'=>'list'
	        		)
	        		, "default"
	        	)        
            );
            
            return;
        }

        $aclId = $this->_request->getParam( 'aclId' );
        if ( empty( $aclId ) ) {
            $this->view->acl = $aclDb->createRow();
            $this->view->acl->role_id = $roleId;
        } else {
            $this->view->acl = $aclDb->find( $aclId )->current();
            if ( empty( $this->view->acl ) ) {
                $this->addError( "acl not found" );
                $this->_redirect(
		            $this->view->url( 
		        		array(
		        			'controller'=>'role' 
		        			,'action'=>'aclList'
		        			,'roleId' => $roleId 
		        		)
		        		, "default"
		        	)        
		        );
                return;
            }
        }

        $form = new Ext_Forms_EditAcl( );
        $form->cancel->setLabel( 'Cancelar' )->setAttrib( 'onclick', "document.location='".
            $this->view->url( 
        		array(
        			'controller'=>'role' 
        			,'action'=>'aclList'
        			,'roleId' => $this->view->acl->role_id 
        		)
        		, "default"
        	)        
	        . "'" );
        $form->accept->setLabel( 'Aceptar' );
        $form->priority->setLabel( 'Prioridad' );
        $form->role->setLabel( 'Role' );
        $form->permission->setLabel( 'Permiso' );
        $form->operation->setLabel( 'Operacion' );
        $form->resource->setLabel( 'Recurso' );

        $resourceDb = Ext_Generic_Model::get( $this->_resourceModel, $this->_db );
        $resourceList = array();
        $resourceList += $resourceDb->getLov();
        $form->resource->addMultiOptions( $resourceList );
        $form->permission->addMultiOptions( self::$PERMISSIONS );

        $data = $this->_request->getParams();

        if ( $this->_request->isPost() ) {

            $isValid = $form->isValid( $data );

            if ( $isValid ) {
                $extraData = array(
                        "priority" => $data[ "priority" ],
                        "role_id" => $data[ "roleId" ],
                        "permission" => strtolower( trim( $data[ "permission" ] ) ),
                        "operation" => $data[ "operation" ],
                        "resource_id" => $data[ "resource" ]
                );
                $this->view->acl->setFromArray( $extraData );
                $this->view->acl->save();

                $this->_redirect( 
					$this->view->url( 
		        		array(
		        			'controller'=>'role' 
		        			,'action'=>'aclList'
		        			,'roleId' => $this->view->acl->role_id 
		        		)
		        		, "default"
					)      
                );
                return;
            }
        }

        // TODO: generalizar esto
        if ( ! isset( $data[ 'role' ] ) ) {
            $data[ 'role' ] = $this->view->acl->findExt_Model_Role()->current()->name;
        }
        if ( ! isset( $data[ 'priority' ] ) ) {
            $data[ 'priority' ] = $this->view->acl->priority;
        }
        if ( ! isset( $data[ 'permission' ] ) ) {
            $data[ 'permission' ] = $this->view->acl->permission;
        }
        if ( ! isset( $data[ 'operation' ] ) ) {
            $data[ 'operation' ] = $this->view->acl->operation;
        }
        if ( ! isset( $data[ 'resource' ] ) ) {
            $data[ 'resource' ] = $this->view->acl->resource_id;
        }
        $form->setAction( 
        	$this->view->url( 
        		array(
        			'controller'=>'role' 
        			,'action'=>'aclEdit'
        			, 'roleId' => $roleId
        			, 'aclId' => $this->view->acl->acl_id 
        		)
        		, "default"
        	)
        );
        $form->populate( $data );
        $this->view->form = $form;
    }

    public function acldeleteAction()
    {
        $roleId = $this->_request->getParam( 'roleId' );
        if ( empty( $roleId ) ) {
            $this->addError( "role not found" );
            $this->_redirect(
	            $this->view->url( 
	        		array(
	        			'controller'=>'role' 
	        			,'action'=>'list'
	        		)
	        		, "default"
	        	)        
            );
            
            return;
        }

        $aclId = $this->_request->getParam( 'aclId' );
        if ( empty( $aclId ) ) {
            $this->addError( "aclId not found" );
            $this->_redirect( 
            	$this->view->url( 
		        	array(
		        		'controller'=>'role' 
		        		,'action'=>'aclList'
		        		,'roleId' => $roleId 
		        	)
		        	, "default"
				)
            );
            return;
        }
        
        $aclDb = Ext_Generic_Model::get( $this->_aclRuleModel, $this->_db );
        $this->view->acl = $aclDb->find( $aclId )->current();
        if ( empty( $this->view->acl ) ) {
            $this->addError( "acl not found" );
            $this->_redirect( 
            	$this->view->url( 
		        	array(
		        		'controller'=>'role' 
		        		,'action'=>'aclList'
		        		,'roleId' => $roleId 
		        	)
		        	, "default"
				)
            );
            return;
        }
        $this->view->acl->delete();
        $this->_redirect( 
            $this->view->url( 
	        	array(
	        		'controller'=>'role' 
	        		,'action'=>'aclList'
	        		,'roleId' => $roleId 
	        	)
	        	, "default"
			)
        );
        
        return;
    }

    public function resourcelistAction()
    {
        $this->view->roleId = $this->_request->getParam( 'roleId' );

        $resourceDb = Ext_Generic_Model::get( $this->_resourceModel, $this->_db );
        $paginator = new Ext_Paginator( $resourceDb->getResourceAsQuery()  );
        $paginator->setCurrentPageNumber( $this->_request->getParam( "page" ) );
        $this->view->paginator = $paginator;
    }

    public function resourceeditAction()
    {
        $this->view->roleId = $this->_request->getParam( 'roleId' );
        
        $resourceDb = Ext_Generic_Model::get( $this->_resourceModel, $this->_db );

        $resourceId = $this->_request->getParam( 'resourceId' );
        if ( empty( $resourceId ) ) {
            $this->view->resource = $resourceDb->createRow();
        } else {
            $this->view->resource = $resourceDb->find( $resourceId )->current();
            if ( empty( $this->view->resource ) ) {
                $this->addError( "resource not found" );
                if ( empty( $this->view->roleId ) ) {
		            $this->_redirect(
			            $this->view->url( 
			        		array(
			        			'controller'=>'role' 
			        			,'action'=>'list'
			        		)
			        		, "default"
			        	)        
		            );
		                	
                } else {
		            $this->_redirect( 
		            	$this->view->url( 
				        	array(
				        		'controller'=>'role' 
				        		,'action'=>'aclList'
				        		,'roleId' => $this->view->roleId 
				        	)
				        	, "default"
						)
		            );
				}
                return;
            }
        }

        $form = new Ext_Forms_EditResource( );
        $form->cancel->setLabel( 'Cancelar' )->setAttrib( 'onclick', "document.location='".
	        $this->view->url( 
	        	array(
	        		'controller'=>'role' 
	        		,'action'=>'resourceList'
	        		,'roleId' => $this->view->roleId  
	        	)
	        	, "default"
			)
        	. "'" 
        );
        $form->accept->setLabel( 'Aceptar' );

        $data = $this->_request->getParams();

        if ( $this->_request->isPost() ) {

            $isValid = $form->isValid( $data );

            // TODO: Make a validator for this
            if ( empty( $this->view->resource->name ) ) {
                $resource = $resourceDb->getResourceId ( $form->getValue('name'), $form->getValue('application_id')  );
                if ( ! empty( $resource ) ) {
                    $this->addError( "El nombre del recurso ya existe" );
                    $isValid = false;
                }
            }

            if ( $isValid ) {
                $extraData = array(
					"name" => strtolower( trim( $data[ "name" ] ) )
                );
                $this->view->resource->setFromArray( $form->getValues() );
                $this->view->resource->save();
                $this->_redirect( 
			        $this->view->url( 
			        	array(
			        		'controller'=>'role' 
			        		,'action'=>'resourceList'
			        		,'roleId' => $this->view->roleId  
			        	)
			        	, "default"
					)
                );
                return;
            }
        }

        // TODO: generalizar esto
        if ( ! isset( $data[ 'name' ] ) ) {
            $data[ 'name' ] = $this->view->resource->name;
            
        }
        $data[ 'name' ] = strtolower( trim($data[ 'name' ] ) );
        $form->setAction( 
	        $this->view->url( 
	        	array(
	        		'controller'=>'role' 
	        		,'action'=>'resourceEdit'
	        		,'roleId' => $this->view->roleId
	        		,'resourceId' => $this->view->resource->resource_id
	        	)
	        	, "default"
			)
        );
        $form->populate( $data );
        $this->view->form = $form;
    }
}
